package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.heima.article.dao.ApArticleDao;
import com.heima.article.service.ApArticleFreemarkerService;
import com.heima.file.MinIOTemplate;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class ArticleFreemarkerServiceImpl implements ApArticleFreemarkerService {
    @Resource
    private Configuration configuration;
    @Resource
    private MinIOTemplate miniOTemplate;
    @Resource
    private ApArticleDao apArticleDao;

    @Override
    public String buildArticle2Minio(Long id, String content) {

        try {
            Template template = configuration.getTemplate("article.ftl");
            Map<String, Object> dataModel = new HashMap<>();
            dataModel.put("content", JSON.parseArray(content));
            StringWriter sw = new StringWriter();
            template.process(dataModel,sw);
            ByteArrayInputStream is = new ByteArrayInputStream(sw.toString().getBytes());
            String url = miniOTemplate.uploadHtmlFile("", id + ".html", is);
            System.out.println(url);


            return  url;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成静态网页失败, 文章id:{},失败原因:{}", id, e.getMessage());
            return null;
        }
    }
}
